package com.springboot.dao.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.springboot.bean.PropertiesBean;

@Configuration
@MapperScan(basePackages = Test2DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "test2SqlSessionFactory")
public class Test2DataSourceConfig {
	public static final String PACKAGE = "com.springboot.mapper.test2";

	@Autowired
	private PropertiesBean propertiesBean;

	@Bean(name = "test2DataSource")
	public DataSource test2DataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(propertiesBean.getMysqlDriverClassName());
		dataSource.setUrl(propertiesBean.getDb2Url());
		dataSource.setUsername(propertiesBean.getDb2User());
		dataSource.setPassword(propertiesBean.getDb2Password());
		return dataSource;
	}

	@Bean(name = "test2TransactionManager")
	public DataSourceTransactionManager test2TransactionManager(@Qualifier("test2DataSource") DataSource test2DataSource) {
		return new DataSourceTransactionManager(test2DataSource);
	}

	@Bean(name = "test2SqlSessionFactory")
	public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource test2DataSource)
			throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(test2DataSource);
		return sessionFactory.getObject();
	}

}
